//
//  MeatCartViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/7/23.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "MeatCartViewController.h"
#import "MeatOrderViewController.h"

#import "MeatCartTableViewCell.h"
#import "MeatCartWholePigCell.h"
#import "MeatShopSectionModel.h"
#import "MeatShopRightModel.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "MeatCartSectionView.h"
#import "MeatPayView.h"
#import "MeatTipLabel.h"

#import "MeatMarketApi.h"


#define rightCellIdentifier @"rightCellIdentifier_meatcart"

@interface MeatCartViewController ()<MeatCartCellDelegate>

@property (nonatomic, strong) MeatTipLabel *tipLabel;
@property (nonatomic, strong) MeatPayView *footer;

@property (nonatomic, strong) MeatMarketApi *meatApi;
@property (nonatomic, strong) MeatCartModel *model;

@property (nonatomic, strong) NSMutableArray *aimsArr;


@end

@implementation MeatCartViewController

#pragma mark - view life cycle

- (void)setupUI{
    
    {
        self.baseNavView.navTitleLabel.text = @"购物车";
        
        [self.baseNavView.rightNavBtn setTitle:@"编辑" forState:UIControlStateNormal];
        self.baseNavView.rightNavBtn.hidden = NO;
        self.baseNavView.rightNavBtn.isNeedAnimation = YES;
    }
   
    {
        __block BOOL selected = NO;
        @weakify(self);
        self.baseNavView.rightNavBtn.tapBlock = ^{
            @strongify(self);
            if (selected) {
                selected = NO;
                [self.baseNavView.rightNavBtn setTitle:@"编辑" forState:UIControlStateNormal];
                self.footer.type = MeatPayType_WholeChoose;
            }else{
                selected = YES;
                [self.baseNavView.rightNavBtn setTitle:@"完成" forState:UIControlStateNormal];
                self.footer.type = MeatPayType_Edit;
            }
        };
    }

    {
        [self.view addSubview:self.tipLabel];
        [self.view addSubview:self.footer];
    }
}


- (void)setupLayout{
    
    _tipLabel.mj_y = self.baseNavView.bottom;
    self.tableView.mj_y = _tipLabel.bottom;
    self.tableView.height = KScreenHeight - (_tipLabel.height + _footer.height +TJ_NavBarHeight);
    _footer.mj_y = self.tableView.bottom ;

}


- (void)initData {
    
    @weakify(self);
    NSNumber *page = [NSNumber numberWithInteger:self.page];
    [[self.meatApi getMyMeatCartListByPage:page] subscribeNext:^(MeatCartModel * _Nullable model) {
        @strongify(self);
        
        if (self.isRefresh) {
            [self endRefresh];
        }
        
        self.model = model;
        MeatCartData *data = model.page;
        
        if ([data.totalCount intValue] < [data.pageSize intValue] ) {
            [self endLoadMoreMoData];
        }else if ([data.totalCount intValue] == [data.pageSize intValue]){
            
            if ([data.currPage intValue] >= [data.totalCount intValue]) {
                [self endLoadMoreMoData];
            }else{
                [self endLoadMore];
            }
        }
        
        if (data.list.count >0) {
            self.tableView.hidden = NO;
            [self.tableView reloadData];
        }else{
            [self loadNoData];
            [self.reloadBtn setImage:[UIImage imageNamed:@"meat_cart_blank"] forState:UIControlStateNormal];
            self.reloadLab.text = @"购物车是空的\n可以去看看有想吃点什么";
            [self.reloadBtn addTarget:self action:@selector(goingBack) forControlEvents:UIControlEventTouchUpInside];
        }
        
    }error:^(NSError * _Nullable error) {
        @strongify(self);
        [self loadErrorData];
    }];
}

- (void)goingBack{
    
    [self.navigationController popViewControllerAnimated:YES];
}

//下拉刷新
- (void)refresh
{
    [super refresh];
    [self resetData];
    [self initData];
}

//上拉加载更多
- (void)loadMore
{
    [super loadMore];
    [self initData];
}

#pragma mark - 折叠按钮点击代理

- (void)clickFoldLabel:(MeatCartTableViewCell *)cell{
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

    MeatCartListModel *sectionModel = self.model.page.list[indexPath.section];
    PigTypeItem *model = sectionModel.validlist[indexPath.row];
    
    model.isOpening = !model.isOpening;
    [self.tableView beginUpdates];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView endUpdates];
}

#pragma mark - tableview delegate/dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.model.page.list.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    MeatCartListModel *cartModel = self.model.page.list[section];
    return cartModel.validlist.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 2) {
        return 110;
    }

    MeatCartListModel *sectionModel = self.model.page.list[indexPath.section];

    if (sectionModel.validlist.count > 0)
    {
        PigTypeItem *model = sectionModel.validlist[indexPath.row];
        if (model.isOpening) {
            // 使用不缓存的方式
            return [self.tableView fd_heightForCellWithIdentifier:rightCellIdentifier configuration:^(id cell) {
                
                [self handleCellHeightWithNewsCell:cell indexPath:indexPath];
            }];
        }else{
            // 使用缓存的方式
            return [self.tableView fd_heightForCellWithIdentifier:rightCellIdentifier cacheByIndexPath:indexPath configuration:^(id cell) {
                
                [self handleCellHeightWithNewsCell:cell indexPath:indexPath];
            }];
        }
    } else{
        
        return 10;
    }
}


// 处理折叠cell高度
-(void)handleCellHeightWithNewsCell:(id)cell indexPath:(NSIndexPath *)indexPath{
    
    MeatCartTableViewCell *newsCell = (MeatCartTableViewCell *)cell;
    MeatCartListModel *sectionModel = self.model.page.list[indexPath.section];
    newsCell.model = sectionModel.validlist[indexPath.row];
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    MeatCartListModel *cartModel = self.model.page.list[section];
    return cartModel.validlist.count >0 ?51 :0;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    if (tableView == self.tableView && section <self.model.page.list.count) {
        
        MeatCartSectionView *sectionView = [[MeatCartSectionView alloc] init];
        MeatCartListModel *cartModel = self.model.page.list[section];
        sectionView.shopName = cartModel.shopName;
        sectionView.isChicked = cartModel.isChicked;

        
        kWeakSelf(self);
        sectionView.dealCartSectionBlock = ^(UIButton *btn) {
            
            if (cartModel.isChicked) {
                
                cartModel.isChicked = NO;
                [cartModel.validlist enumerateObjectsUsingBlock:^(PigTypeItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    PigTypeItem *model = (PigTypeItem *)obj;
                    model.isChicked = NO;
                }];
            }else{
                
                cartModel.isChicked = YES;
                [cartModel.validlist enumerateObjectsUsingBlock:^(PigTypeItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    PigTypeItem *model = (PigTypeItem *)obj;
                    model.isChicked = NO;
                }];
            }

            [weakself localReloadTableViewBySection:section];
        };
        
        return cartModel.validlist.count >0 ?sectionView :nil;
    }
    return nil;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MeatCartListModel *sectionModel = self.model.page.list[indexPath.section];
    PigTypeItem *model = sectionModel.validlist[indexPath.row];

    if (indexPath.section == 2) {
        MeatCartWholePigCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatCartWholePigCell"];
        //cell.newsModel = model;
        
        kWeakSelf(self);
        cell.chooseCartBlock = ^(UIButton *btn) {
            model.isChicked = model.isChicked ?NO :YES;
            [weakself localReloadTableViewBySection:indexPath.section];
        };
        return cell;
    }
    

    MeatCartTableViewCell *newsCell = [tableView dequeueReusableCellWithIdentifier:rightCellIdentifier];
    newsCell.cellDelegate = self;
    newsCell.model = model;

    //单个选择cellBlock
    kWeakSelf(self);
    newsCell.chooseCartBlock = ^(UIButton *btn) {
        model.isChicked = model.isChicked ?NO :YES;
        [weakself localReloadTableViewBySection:indexPath.section];
    };
    
    return newsCell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - setter and getter

- (MeatTipLabel *)tipLabel{
    if (!_tipLabel) {
        _tipLabel = [[MeatTipLabel alloc] init];
        _tipLabel.hidden = YES;
        _tipLabel.height = 34;
        
        NSString *contentStr = @" 购物车中有3件商品已无货，点击查看";
        NSMutableAttributedString *aims = [contentStr createAttributingByIcon:@"meat_cart_tip" downIndexImage:nil textColor:UIColorFromRGB(0xEC8C00) font:mFont(12)];
        _tipLabel.attributedText = aims;
    }
    return _tipLabel;
}


- (MeatPayView *)footer{
    if (!_footer) {
        _footer = [[MeatPayView alloc] init];
        _footer.type = MeatPayType_WholeChoose;
        _footer.hidden = YES;
        
        //全选Block
        kWeakSelf(self)
        _footer.chooseCartBlock = ^(UIButton *btn) {
            
            if (btn.selected) {
                [weakself.aimsArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    MeatShopSectionModel *sectionModel = (MeatShopSectionModel *) obj;
                    sectionModel.isChicked = NO;
                    [sectionModel.rows enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        
                        MeatShopRightModel *model = (MeatShopRightModel *)obj;
                        model.isChicked = NO;
                        [weakself.tableView reloadData];
                    }];
                }];

            }else{
                [weakself.aimsArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    MeatShopSectionModel *sectionModel = (MeatShopSectionModel *) obj;
                    sectionModel.isChicked = YES;
                    
                    [sectionModel.rows enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        
                        MeatShopRightModel *model = (MeatShopRightModel *)obj;
                        model.isChicked = YES;
                        [weakself.tableView reloadData];
                    }];
                }];
            }
        };
        
        
        //支付Block
        _footer.payCartBlock = ^{
            
            MeatOrderViewController *vc = [[MeatOrderViewController alloc] init];
            [weakself.navigationController pushViewController:vc animated:YES];
        };
        
        //清除Block
        _footer.clearCartBlock = ^{
            
        };
        
        //删除Block
        _footer.deleteCartBlock = ^{
            
            [weakself.aimsArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                MeatShopSectionModel *sectionModel = (MeatShopSectionModel *) obj;
                NSMutableArray *aims = [NSMutableArray arrayWithArray:sectionModel.rows];

                [aims enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    MeatShopRightModel *model = (MeatShopRightModel *)obj;
                    if (model.isChicked) {
                        [aims removeObject:model];
                    }
                }];
                
                sectionModel.rows = aims;
            }];
            
            [weakself.tableView reloadData];

        };
    }
    return _footer;
}


- (NSMutableArray *)aimsArr{
    if (!_aimsArr) {
        _aimsArr = [NSMutableArray array];
    }
    return _aimsArr;
}


- (MeatMarketApi *)meatApi
{
    if(!_meatApi){
        _meatApi = [[MeatMarketApi alloc]init];
    }
    return _meatApi;
}

- (MeatCartModel *)model
{
    if (!_model) {
        _model = [[MeatCartModel alloc] init];
    }
    return _model;
}


#pragma mark - other methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
    CGFloat sectionHeaderHeight = 51;
    if(scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}


#pragma mark - override methods

- (void)registerTableViewCell{
    [self.tableView setHidden:YES];
    [self.tableView registerClass:[MeatCartTableViewCell class] forCellReuseIdentifier:rightCellIdentifier];
    [self.tableView registerClass:[MeatCartWholePigCell class] forCellReuseIdentifier:@"MeatCartWholePigCell"];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 10)];
    view.backgroundColor = mBackgroudColor;
    self.tableView.tableFooterView = view;
}

- (void)loadErrorData
{
    [super loadErrorData];
    self.footer.hidden = YES;
    self.tipLabel.hidden = YES;
}

- (void)loadNoData
{
    [super loadNoData];
    self.footer.hidden = YES;
    self.tipLabel.hidden = YES;
}


- (void)endLoadMore{
    [super endLoadMore];
    self.footer.hidden = NO;
    self.tipLabel.hidden = NO;
}

- (void)endRefresh{
    [super endRefresh];
    self.footer.hidden = NO;
    self.tipLabel.hidden = NO;
}

- (void)endLoadMoreMoData
{
    [super endLoadMoreMoData];
    self.footer.hidden = NO;
    self.tipLabel.hidden = NO;
}



@end
